<template>
  <van-cell title="我的评论" center></van-cell>
  <van-list
    v-model:loading="loadingComment"
    :finished="finishedComment"
    finished-text="没有更多了"
  >
    <van-cell v-for="comment in listComment" :key="comment.id">
      <van-row class="van-rowstyle">
        <van-col>
          <van-image
            round
            fit="cover"
            :src="comment.useravatar"
            width="2rem"
            height="2rem"
          />
        </van-col>
        <van-col class="usernamestyle" offset="1">
          {{ comment.username }}
        </van-col>
      </van-row>
      <van-row class="van-rowstyle" justify="space-between">
        <van-col class="contentstyle" offset="3">
          {{ comment.content }}
        </van-col>
      </van-row>
      <van-row class="van-rowstyle" justify="space">
        <van-col offset="3" v-for="img in comment.imagepath" :key="img">
          <van-image :src="img" fit="cover" width="6.5rem" height="6.5rem"
            ><template v-slot:error>加载失败</template></van-image
          >
        </van-col>
      </van-row>
      <van-row class="van-rowstyle" justify="end">
        <van-col>
          {{ comment.createTime }}
        </van-col>
        <van-col
          class="delstyle"
          offset="1"
          @click="beforeDelete(comment.id, comment.flag)"
        >
          删除
        </van-col>
      </van-row>
    </van-cell>
  </van-list>

  <van-overlay :show="showDelete" z-index="2">
    <van-popup :style="{ padding: '64px' }">
      <van-cell-group inset>
        <van-button text="确定删除" @click="DeleteComment" />
        <van-button text="取消" @click="showDelete = false" />
      </van-cell-group>
    </van-popup>
  </van-overlay>
</template>

<script>
import { ref } from "vue";
import MyAxios from "@/plugins/MyAxios";
import { showNotify } from "vant";
import store from "@/store";

export default {
  setup() {
    const backPath = ref(store.state.backedPath);
    const loadingComment = ref(true);
    const finishedComment = ref(false);
    const listComment = ref([]);

    const formatTimeDifference = (timeString) => {
      const now = new Date();
      const createTime = new Date(timeString);
      const diff = now - createTime;
      let result;

      if (diff < 0) {
        result = "未来时间";
      } else if (diff < 1000 * 60) {
        // 小于1分钟
        result = `${Math.floor(diff / 1000)} 秒前`;
      } else if (diff < 1000 * 60 * 60) {
        // 小于1小时
        result = `${Math.floor(diff / (1000 * 60))} 分钟前`;
      } else if (diff < 1000 * 60 * 60 * 24) {
        // 小于1天
        result = `${Math.floor(diff / (1000 * 60 * 60))} 小时前`;
      } else {
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        result = `${days} 天前`;
      }

      return result;
    };

    const loadComment = () => {
      return MyAxios.get("/comment/getCommentByLoginUser");
    };

    const loadCommentRq = () => {
      return MyAxios.get("/commentrq/getCommentRqByLoginUser");
    };

    Promise.all([loadComment(), loadCommentRq()]).then(function ([
      response,
      response2,
    ]) {
      for (let i = 0; i < response.data.length; i++) {
        const {
          content,
          createTime,
          id,
          isDelete,
          postId,
          updateTime,
          userId,
          anon,
          anon_name,
          imgpath,
        } = response.data[i];
        const username = ref("");
        const useravatar = ref("");
        MyAxios.get("/user/get/login").then((res) => {
          const { userAvatar, userName } = res.data;

          if (userAvatar === null || anon === 1) {
            useravatar.value = store.state.anonImg;
          } else {
            useravatar.value =
              "http://" + backPath.value + "/api/userimages/" + userAvatar;
          }
          if (anon === 1) {
            username.value = anon_name;
          } else {
            username.value = userName;
          }
        });

        let imagePaths = [];
        try {
          imagePaths = JSON.parse(imgpath || "[]"); // 尝试解析 imgpath，同样处理空值或错误格式
        } catch (error) {
          console.error("Parsing imgpath failed:", error);
          imagePaths = []; // 解析失败时使用空数组
        }

        // 处理 imagePaths（如果需要的话）
        imagePaths = imagePaths.map(
          (path) => `http://${backPath.value}/api/commentimages/${path}`
        );
        listComment.value.push({
          content,
          createTime: formatTimeDifference(createTime),
          id,
          isDelete,
          postId,
          updateTime,
          userId,
          username,
          useravatar,
          anon,
          anon_name,
          flag: 0,
          imagepath: imagePaths,
        });
      }
      for (let i = 0; i < response2.data.length; i++) {
        const {
          content,
          createTime,
          id,
          isDelete,
          postId,
          updateTime,
          userId,
          anon,
          anon_name,
          imgpath,
        } = response2.data[i];
        const username = ref("");
        const useravatar = ref("");
        MyAxios.get("/user/get/login").then((res) => {
          const { userAvatar, userName } = res.data;

          if (userAvatar === null || anon === 1) {
            useravatar.value = store.state.anonImg;
          } else {
            useravatar.value =
              "http://" + backPath.value + "/api/userimages/" + userAvatar;
          }
          if (anon === 1) {
            username.value = anon_name;
          } else {
            username.value = userName;
          }
        });

        let imagePaths = [];
        try {
          imagePaths = JSON.parse(imgpath || "[]"); // 尝试解析 imgpath，同样处理空值或错误格式
        } catch (error) {
          console.error("Parsing imgpath failed:", error);
          imagePaths = []; // 解析失败时使用空数组
        }

        // 处理 imagePaths（如果需要的话）
        imagePaths = imagePaths.map(
          (path) => `http://${backPath.value}/api/commentrqimages/${path}`
        );
        listComment.value.push({
          content,
          createTime: formatTimeDifference(createTime),
          id,
          isDelete,
          postId,
          updateTime,
          userId,
          username,
          useravatar,
          anon,
          anon_name,
          flag: 1,
          imagepath: imagePaths,
        });
      }
      loadingComment.value = false;
      finishedComment.value = true;
    });

    listComment.value = listComment.value.sort(
      (a, b) => new Date(b.updateTime) - new Date(a.updateTime)
    );

    const showDelete = ref(false);
    const DeleteCommentId = ref(0);
    const DeleteFlag = ref(0);
    const beforeDelete = (commentId, flag) => {
      showDelete.value = true;
      DeleteCommentId.value = commentId;
      DeleteFlag.value = flag;
    };

    const DeleteComment = () => {
      let path = "";
      if (DeleteFlag.value === 0) {
        path = "/comment/deleteComment";
      } else {
        path = "/commentrq/deleteCommentRq";
      }

      MyAxios.post(path, {
        id: DeleteCommentId.value,
      }).then((res) => {
        const { code, message } = res;
        if (code === 0) {
          showNotify({ type: "success", message: "删除成功" }, 500);
          setTimeout(() => {
            location.reload();
          }, 500);
        } else {
          showNotify({ type: "warning", message: message });
        }
      });
      showDelete.value = false;
    };
    return {
      loadingComment,
      finishedComment,
      listComment,
      showDelete,
      beforeDelete,
      DeleteComment,
    };
  },
};
</script>

<style scoped>
.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 1px;
  line-height: 2px;
  text-align: center;
  background-color: #39a9ed;
}

.contentstyle {
  /* 调整字体大小 */
  font-size: 16px; /* 或者您想要的任何大小 */

  color: black;
  text-align: left;
  line-height: 1.6;
  /* 调整字体类型 */
  font-family: Arial, sans-serif; /* 或者您喜欢的任何字体 */
}

.usernamestyle {
  font-size: 15px;
  line-height: 1.5;
  color: #394968;
}

/* 调整行之间的间距 */
.van-rowstyle {
  margin-bottom: 5px; /* 在每行下方添加间距 */
}
.delstyle {
  color: #00a0fd;
}
</style>
